<script setup lang="ts">
import {getCurrentInstance} from "vue";
import {read, Sheet, utils, WorkBook} from "xlsx";
// 交易趋势
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import TradeChart from "~/contentScripts/views/sycm/frame_trade_overview/TradeChart.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {isLogin} from "~/logic";
import SYCM from "~/utils/ali/sycm";

const loginVisible = ref(false);
const visible = ref(false);

const dataSource = ref<any[]>([]);
const columns = ref<Object[]>([]);
// 判断是否在frame下运行
const isFrame: boolean = window.location.href.includes('bda/tradinganaly/overview/overview.htm');
const isTop: boolean = window.top === window.self;
const loading = ref(false);
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = async () => {
  if (isLogin({
    emit: () => {
      loginVisible.value = true;
    }
  }, __option)) {
    loading.value = true;
    let downloadParams: any = await SYCM.getInternalFiberData("#trading-interpretion > div > div.navbar > div > div.ui-download.navbar-download > a", '_currentElement.props.children[0]._owner._currentElement.props');
    let baseUrl;
    let params: any = {};
    try {
      baseUrl = downloadParams.baseUrl;
      params = {
        categoryId: downloadParams.downloadParam.categoryId.requestValue,
        dateRange: downloadParams.downloadParam.dateRange.requestValue,
        dateType: downloadParams.downloadParam.dateType.requestValue,
        diff: downloadParams.downloadParam.diff.requestValue,
      }
    } catch (e) {
      // console.log(e, downloadParams);
      baseUrl = 'https://sycm.taobao.com/bda/download/excel/tradinganaly/overview/TendencyExcel.do';
      let domHtml = document.querySelector("#trading-interpretion > div > div.navbar > div > div.ui-datepicker.navbar-datepicker.last30 > span")?.innerHTML;
      // 删除domHtml中的注释和空格
      domHtml = domHtml?.replace(/<!--[\s\S]*?-->/g, "").replace(/\s/g, "");
      // console.log(domHtml?.split('-'));
      let startDate = domHtml?.split('~')[0];
      let endDate = domHtml?.split('~')[1];
      params = {
        dateRange: startDate + '|' + endDate,
        dateType: 'recent30',
        diff: 0,
      }
    }
    // 把baseUrl和params拼接成url
    let url = baseUrl + '?';
    for (let key in params) {
      url += key + '=' + params[key] + '&';
    }
    url = url.substring(0, url.length - 1);
    dataSource.value = [];
    window.fetch(url).then(response => response.blob()).then(blob => {
      const reader = new FileReader();
      reader.readAsBinaryString(blob);
      reader.onload = function (e) {
        const data = e.target?.result;
        const workbook: WorkBook = read(data, {type: 'binary'});
        const sheet: Sheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData: any[] = utils.sheet_to_json(sheet, {
          header: 1,
          range: 3,
        });
        const tableData: any[] = [];
        const column: any[] = [];
// 遍历 jsonData，构建二维数组
        for (let i = 1; i < jsonData.length; i++) {
          const row: any = {};
          for (let j = 0; j < jsonData[i].length; j++) {
            const header = jsonData[0][j];
            // 把header加入columns
            if (i == 1) {
              if (header == '终端') {
                column.push({
                  title: header,
                  dataIndex: header,
                  key: header,
                  width: header.length * 14 + 20,
                  align: 'center',
                  dataType: 'custom',
                  slot: 'terminal',
                })
                column.push({
                  title: '访客数',
                  dataIndex: '访客数',
                  key: '访客数',
                  width: '访客数'.length * 14 + 20,
                })
              } else if (header == '日期') {
                column.push({
                  title: header,
                  dataIndex: header,
                  key: header,
                  width: header.length * 14 + 20,
                  fixed: 'left',
                })
              } else {
                column.push({
                  title: header,
                  dataIndex: header,
                  key: header,
                  width: header.length * 14 + 20,
                })
              }
            }
            row[header] = jsonData[i][j];
            try {
              if (row['支付转化率']==0 || row['支付买家数'] == 0){
                row['访客数'] = 0;
              }else {
                row['访客数'] = parseInt(parseInt(row['支付买家数']) / (parseInt(row['支付转化率']) / 100));
              }
            } catch (e) {
              // console.log(e);
              row['访客数'] = 0;
            }
          }
          if (Object.keys(row).length>0){
            tableData.push(row);
          }
        }
        loading.value = false;
        // 通知父级窗口
        window.parent.postMessage({
          type: '_xc_showModal',
          columns: JSON.stringify(column),
          dataSource: JSON.stringify(tableData)
        });
      }
    })
  }
}
if (isTop) {
  let listener = function (e: any) {
    if (e.data.columns && e.data.dataSource && e.data.type == '_xc_showModal') {
      columns.value = JSON.parse(e.data.columns);
      // 给columns注入sorter
      columns.value.forEach((item: any) => {
        if (item.dataIndex == '终端') {
          item.sorter = (a: any, b: any) => a[item.dataIndex].localeCompare(b[item.dataIndex]);
        } else if (item.dataIndex == '日期') {
          item.sorter = (a: any, b: any) => new Date(a[item.dataIndex]).getTime() - new Date(b[item.dataIndex]).getTime();
          item.defaultSortOrder = 'ascend';
        } else {
          item.sorter = (a: any, b: any) => parseInt(a[item.dataIndex]) - parseInt(b[item.dataIndex]);
        }
      })
      dataSource.value = JSON.parse(e.data.dataSource);
      visible.value = true;
    }
  };
  onMounted(() => {
    // console.log('addListener');
    window.addEventListener("message", listener);
  })
  onBeforeUnmount(() => {
    window.removeEventListener("message", listener);
  })
}
</script>

<template>
  <base-app>
    <template v-if="isFrame">
      <a-button-group>
        <user @login="loginVisible=true" :style="{
        marginRight: '0'
      }"
        />
        <a-button :loading="loading" type="primary" size="small" @click="handle">一键转化</a-button>
      </a-button-group>
      <user-login-modal v-model:visible="loginVisible" @close="loginVisible=false"/>
    </template>
    <a-modal v-if="isTop" title="交易-交易概况-交易趋势" :footer="false" width="95%" style="top: 20px;"
             v-model:visible="visible"
    >

      <div style="max-height: calc(100vh - 150px);overflow-y: auto;">
        <TradeChart :data="dataSource" :columns="columns"/>
        <a-divider/>
        <base-table table-name="交易-交易概况-交易趋势" :scroll="{
          y:450,
        }" :columns="columns" size="small" :data-source="dataSource"
        >
          <template #terminal="row">
            <a-tag color="green" v-if="row.终端.indexOf('pc')>-1">PC端</a-tag>
            <a-tag color="yellow" v-else-if="row.终端.indexOf('无线端')>-1">无线端</a-tag>
            <a-tag color="blue" v-else>全部终端</a-tag>
          </template>
        </base-table>

      </div>
    </a-modal>
  </base-app>
</template>

<style scoped>

</style>
